<script setup lang="ts">
import type { FieldRule, FormInstance } from '@arco-design/web-vue'

import { modeStatusOptions } from '@/constants/dns'

interface IEmit {
  (event: 'update:ip', value: string): void
  (event: 'update:status', value: number): void
  (event: 'add'): void
  (event: 'delete'): void
}

interface IProps {
  disableDelete?: boolean
  disableAdd?: boolean
  disabledAll?: boolean
  ip: string
  status: number
}
const props = withDefaults(defineProps<IProps>(), {
  disableDelete: false,
  disableAdd: false,
  disabledAll: false,
})
const emit = defineEmits<IEmit>()
/**
 * 字段配置列表
 */
const formRef = ref<FormInstance>()
const formData = reactive({
  ip: '',
  status: 1,
})
// ip格式校验
function validateIp(value: string | number | (string | number)[], callback) {
  if (!value)
    return callback('地址 IP 不能为空')
  if (!regexpMap.ipv4.test(String(value)))
    return callback('地址 IP 格式错误')
  callback()
}
const formRules = computed<{ [key: string]: FieldRule[] }>(() => {
  return {
    ip: [{ required: true, validator: validateIp }],
    status: [{ required: true, message: '请选择模式', trigger: 'change' }],
  }
})

function handleIpChange(val: string) {
  emit('update:ip', val)
}
function handleModeChange(val: number) {
  emit('update:status', val)
}

function setValue() {
  emit('update:ip', formData.ip)
  emit('update:status', formData.status)
}
async function validate() {
  setValue()
  return await formRef.value?.validate()
}
defineExpose({
  validate,
})
onMounted(() => {
  formData.ip = props.ip
  formData.status = props.status
  setValue()
})
</script>

<template>
  <a-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    inline
    class="address-mode"
  >
    <!-- 字段 -->
    <a-form-item
      field="ip"
      hide-asterisk
      class="!w-[192px]"
      hide-label
    >
      <a-input
        v-model="formData.ip"
        placeholder="请输入地址 IP"
        class="!w-full"
        @change="handleIpChange"
      />
    </a-form-item>
    <a-form-item
      field="status"
      hide-asterisk
      class="!mx-4 !w-[128px]"
      hide-label
    >
      <a-select
        v-model="formData.status"
        placeholder="请选择"
        class="!w-full"
        :disabled="disabledAll"
        :options="modeStatusOptions"
        @change="handleModeChange"
      />
    </a-form-item>
    <div class="action h-8 flex items-center justify-start !w-8">
      <a-link
        :disabled="disableDelete || disabledAll"
        status="danger"
        :hoverable="false"
        long
        @click="emit('delete')"
      >
        <i-icons-delete />
      </a-link>
    </div>
  </a-form>
</template>

<style scoped lang="less"></style>
